package com.icehelper.hades.base.util;

import java.security.Key;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

/**
 * 加密工具类
 *
 * @author Leon Sun
 */
public class EncryptUtil {

  private static final int SIZE = 16;

  private static final String aesType = "AES/ECB/PKCS5Padding";

  private static final String iv = "manhattan_financing_iv";

  private static final String keyAlgorithm = "AES";

  private static final String digestAlgorithm = "SHA-256";

  /**
   * AES加密
   *
   * @param content 原始内容
   * @param secretKey 加密密钥
   */
  public static byte[] aesEncrypt(byte[] content, byte[] secretKey) {
    try {

      MessageDigest digest = MessageDigest.getInstance(digestAlgorithm);
      digest.update(secretKey);
      byte[] keyBytes = new byte[SIZE];
      System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);

      Key keySpec = new SecretKeySpec(keyBytes, keyAlgorithm);
      Cipher cipher = Cipher.getInstance(aesType);
      cipher.init(Cipher.ENCRYPT_MODE, keySpec);

      byte[] res = cipher.doFinal(content);
      return res;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * AES加密
   *
   * @param content 原始内容
   * @param secretKey 密钥
   */
  public static String aesEncrypt(String content, String secretKey) {
    return Base64.encodeBase64String(aesEncrypt(content.getBytes(), secretKey.getBytes()));
  }


  /**
   * AES解密
   *
   * @param content 密文
   * @param secretKey 密钥
   */
  public static byte[] aesDecrypt(byte[] content, byte[] secretKey) {
    try {
      MessageDigest digest = MessageDigest.getInstance(digestAlgorithm);
      digest.update(secretKey);
      byte[] keyBytes = new byte[SIZE];
      System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);

      SecretKeySpec keySpec = new SecretKeySpec(keyBytes, keyAlgorithm);
      Cipher cipher = Cipher.getInstance(aesType);
      cipher.init(Cipher.DECRYPT_MODE, keySpec);

      return cipher.doFinal(content);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * AES解密
   *
   * @param content 密文
   * @param secretKey 密钥
   */
  public static String aesDecrypt(String content, String secretKey) {
    return new String(aesDecrypt(Base64.decodeBase64(content), secretKey.getBytes()));
  }

}
